package com.mapapp.flutter_mapapp.service;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;

import com.blankj.utilcode.util.ActivityUtils;
import com.buihha.audiorecorder.Mp3Recorder;
import com.mapapp.flutter_mapapp.activity.NewDataActivity;
import com.mapapp.flutter_mapapp.util.SortableUUID;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class AudioRecordService extends Service {
    private static final String TAG = "AudioRecordService";
    private Mp3Recorder mRecorder;
    public static final String FILE_DIR = Environment.getExternalStorageDirectory()
            + File.separator + "Sounds";

    public static String audioName;

    private Timer mTimer;

    private static boolean mIsServerRun = false;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mIsServerRun = true;
        audioName = SortableUUID.randomUUID() + ".mp3";
        mRecorder = new Mp3Recorder();
        mRecorder.setOnRecordListener(new Mp3Recorder.OnRecordListener() {
            @Override
            public void onStart() {
                //开始录音
            }

            @Override
            public void onStop() {
                //停止录音
            }

            @Override
            public void onRecording(int i, double v) {
//                Log.d("MainActivity", "采样:" + i + "Hz   音量:" + v + "分贝");
            }
        });

        mTimer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                if (!ActivityUtils.isActivityExistsInStack(NewDataActivity.class)) {
                    stopSelf();
                }
            }
        };
        //30s查询一次当前activity是否存活，不存活的话直接stop
        mTimer.schedule(timerTask, 0, 1000 * 30);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!mRecorder.isRecording()) {
            try {
                File file = new File(FILE_DIR, audioName);
                if (file.exists()) {
                    file.delete();
                }
                mRecorder.startRecording(FILE_DIR, audioName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        mIsServerRun = false;
        if (mTimer != null) {
            mTimer.cancel();
        }
        if (mRecorder != null && mRecorder.isRecording()) {
            mRecorder.stopRecording();
        }
    }

    public static boolean getIsServerRun() {
        return mIsServerRun;
    }
}
